<?

class {$name}_base_peer
{
	const DB = '{$project}';
	const COLLECTION = '{$name}';

	public static function get( $id )
	{
		if ( ($data = cache::get(self::COLLECTION . $id)) !== false ) return $data;
		
		$data = db_mongo::col(self::DB, self::COLLECTION)->findOne( array('_id' => new MongoID($id)) );
		cache::set(self::COLLECTION . $id, $data);

		return $data;
	}

	public static function get_by($name, $value)
	{
		return db_mongo::col(self::DB, self::COLLECTION)->findOne( array($name => $value) );
	}

	public static function get_list($params  = array())
	{
		return db_mongo::col(self::DB, self::COLLECTION)->find( $params );
	}

	public static function insert( array $data )
	{
		db_mongo::col(self::DB, self::COLLECTION)->insert( $data );
		return $data['_id'];
	}

	public static function save( $id, array $data, $upsert = false )
	{
		$key = array_shift(array_keys($data));
		if ( $key{0} != '$' ) $data = array( '$set' => $data );

		db_mongo::col(self::DB, self::COLLECTION)->update(
			array('_id' => new MongoId($id)),
			$data,
			array('upsert' => $upsert)
		);

		cache::delete(self::COLLECTION . $id);
	}

	public static function delete( $id )
	{
		db_mongo::col(self::DB, self::COLLECTION)->remove(
			array('_id' => new MongoId($id))
		);

		cache::delete(self::COLLECTION . $id);
	}

	public static function drop()
	{
		return db_mongo::col(self::DB, self::COLLECTION)->drop();
	}
}